package com.jjty.dataGenerator.bg.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjty.dataGenerator.bg.entity.*;
import com.jjty.dataGenerator.bg.mapper.StudentInfoMapper;
import com.jjty.dataGenerator.bg.service.StudentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author leikk
 * @since 2025-03-19
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements StudentInfoService {

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Value("${sc202527.apiUrl}")
    private String apiUrl;

    @Override
    public boolean importStudents(List<StudentInfo> students) {
        return saveBatch(students);
    }

    @Override
    public Page getStudentPage(Page page, StudentInfo param, String keyword) {
        page.setOptimizeCountSql(false);
        List<StudentInfo> studentInfos = studentInfoMapper.getStudentPage(page,param,keyword);
        return page.setRecords(studentInfos);
    }

    @Override
    public ScStudentInfoResponse[] saveStudentInfo(ScStudentInfoRequest request) {
        String url = apiUrl + "/typt" + "/get_student_open_info";
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头为 application/x-www-form-urlencoded
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 构建请求参数
        MultiValueMap<String, String> requestParam = new LinkedMultiValueMap<>();
        // 构建 receiverMobiles 的 JSON 数组
        JSONArray receiverMobilesArray = new JSONArray();
        for (String mobile : request.getReceiverMobiles()) {
            receiverMobilesArray.add(mobile);
        }
        // 将数据转换为 JSON 字符串并作为一个参数传递
        String dataJson = "{\"groupId\": \"" + request.getGroupId() + "\",\"thirdAppId\":\"" + request.getThirdAppId() + "\",\"receiverMobiles\":" + receiverMobilesArray.toJSONString() + "}";
        requestParam.add("data", dataJson);
        System.out.println("----------"+dataJson);
        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestParam, headers);
        // 发送 POST 请求并接收响应
        ResponseEntity<ScStudentInfoResponse[]> responseEntity = restTemplate.postForEntity(url, requestEntity, ScStudentInfoResponse[].class);
        System.out.println(responseEntity.getBody());
        // 获取响应体
        ScStudentInfoResponse[] responseArray = responseEntity.getBody();

        if (responseArray != null && responseArray.length > 0) {
            // 将数组转换为列表
            List<ScStudentInfoResponse> responseList = Arrays.asList(responseArray);
            // 保存所有数据到数据库，使用自定义插入方法
            studentInfoMapper.insertScClassStudent(responseList);
            return responseArray;
        }
        return null;
    }

    @Override
    public ScClassStudentByXZN saveAllStudent(ScClassStudentRequestByXZN request) {
        String url = apiUrl + "/typt" + "/all_card_detail";
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头为 application/x-www-form-urlencoded
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 构建请求参数
        MultiValueMap<String, String> requestParam = new LinkedMultiValueMap<>();
        // 将数据转换为 JSON 字符串并作为一个参数传递
        String dataJson = "{\"corpid\": \"" + request.getCorpid() + "\",\"ec_code\":\"" + request.getEc_code() + "\",\"appid\":\"" + request.getAppid() + "\"}";
        requestParam.add("data", dataJson);
        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestParam, headers);
        // 发送 POST 请求并接收响应
        // 修改反序列化类型为 ScClassStudent 而不是 ScClassStudent[]
        ResponseEntity<ScClassStudentByXZN> responseEntity = restTemplate.postForEntity(url, requestEntity, ScClassStudentByXZN.class);
        System.out.println(responseEntity.getBody());
        // 获取响应体
        ScClassStudentByXZN responseObject = responseEntity.getBody();

        if (responseObject != null) {
            // 保存到数据库，使用自定义插入方法
            studentInfoMapper.insertScClassStudentByXZN(responseObject);
            return responseObject;
        }
        return null;
    }

}
